<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 商品列表搜索与添加功能 -->
      <el-row :gutter="20">
        <!-- 商品列表搜索框 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button icon="el-icon-search" slot="append" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加商品 -->
        <el-col :span="4">
          <el-button type="primary" @click="toAddpage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 商品列表区域 -->
      <el-table
      :data="goodsList"
      border
      stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column label="商品价格(元)" prop="goods_price" width="95px"></el-table-column>
        <el-table-column label="商品重量" prop="goods_weight" width="70px"></el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="200px">
          <template slot-scope="scope">
            {{scope.row.add_time | dateFormat}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getGoodsInfo(scope.row.goods_id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeGoods(scope.row.goods_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 编辑商品对话栏 -->
    <el-dialog
      title="编辑商品"
      :visible.sync="setGoodsDialogVisible"
      width="50%"
      @close="setGoodsDialogClosed">
      <el-form :model="goodsForm" label-width="100px"
      ref="goodsFormRef"
      label-position="top">
        <el-tabs :tab-position="'left'" v-model="activeIndex">
          <!-- 商品基本信息tab栏 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格(元)" prop="goods_price">
              <el-input v-model="goodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="goodsForm.goods_cat"
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  value: 'cat_id',
                  label: 'cat_name',
                  children: 'children'
                }"
                clearable
                @change="cateChange"
                ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品静态属性编辑栏 -->
          <el-tab-pane label="商品属性" name="1">
            <el-form-item
            v-for="(item, i) in this.goodsForm.attrs"
            :key="i"
            :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品图片上传 -->
          <el-tab-pane label="商品图片" name="2">
            <el-upload
              :action="this.uploadURL"
              :headers="headersObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="goodsForm.pics"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>

          <!-- 商品内容编辑区域 -->
          <el-tab-pane label="商品内容" name="3">
            <quill-editor v-model="goodsForm.goods_introduce"></quill-editor>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setGoodsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setGoodsInfo">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 商品图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%">
      <el-image :src="previewPath"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  data () {
    return {
      // 商品列表配置信息
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 商品列表
      goodsList: [],
      // 商品总条数
      total: 0,
      // 编辑商品对话框的显示与隐藏
      setGoodsDialogVisible: false,
      // 要编辑的商品信息
      goodsForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      cateList: [],
      activeIndex: 0,
      // 上传商品图片的URL
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传商品图片的token请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 商品图片的预览地址
      previewPath: '',
      previewDialogVisible: false,
      rules: {
        goods_name: { required: true, message: '请输入商品名称', trigger: 'blur' },
        goods_price: { required: true, message: '请输入商品价格', trigger: 'blur' },
        goods_weight: { required: true, message: '请输入商品重量', trigger: 'blur' },
        goods_number: { required: true, message: '请输入商品数量', trigger: 'blur' },
        goods_cat: { required: true, message: '请选择商品分类', trigger: 'change' }
      }
    }
  },
  created () {
    this.getGoodsList()
  },
  computed: {
    // 获取当前选中的分类id
    cateId () {
      if (this.goodsForm.goods_cat.length === 3) {
        return this.goodsForm.goods_cat[2]
      }
      return []
    }
  },
  methods: {
    // 获取商品列表
    async getGoodsList () {
      const { data: res } = await this.$http.get('goods', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取商品列表失败！')
      this.$message.success('获取商品列表成功！')
      this.goodsList = res.data.goods
      this.total = res.data.total
    },
    // 商品列表每页显示的数量
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getGoodsList()
    },
    // 控制商品列表的当前页码
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getGoodsList()
    },
    // 获取商品信息
    async getGoodsInfo (id) {
      const { data: res } = await this.$http.get(`goods/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取商品信息失败！')
      this.$message.success('获取商品信息成功！')
      this.goodsForm.goods_name = res.data.goods_name
      this.goodsForm.goods_price = res.data.goods_price
      this.goodsForm.goods_weight = res.data.goods_weight
      this.goodsForm.goods_number = res.data.goods_number
      this.goodsForm.goods_cat = res.data.goods_cat.split(',').map(Number)
      console.log(this.goodsForm.goods_cat)
      res.data.pics.forEach(item => {
        const newPics = {
          name: item.pics_id,
          url: item.pics_big.replace('_800x800', '')
        }
        this.goodsForm.pics.push(newPics)
      })
      console.log(this.goodsForm.pics)
      this.goodsForm.goods_introduce = res.data.goods_introduce
      this.goodsForm.attrs = res.data.attrs
      this.getCateList()
      console.log(res)
      this.setGoodsDialogVisible = true
    },
    // 编辑商品
    setGoodsInfo () {
      this.$refs.goodsFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请完善商品信息！')
        // 通过loadsh的cloneDeep进行深拷贝
        const form = _.cloneDeep(this.goodsForm)
        form.goods_cat = form.goods_cat.join(',')

        form.attrs = this.goodsForm.attrs
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('编辑商品信息失败！')
        this.$message.success('编辑商品信息成功！')
        this.$router.push('/goods')
      })
    },
    // 删除商品
    async removeGoods (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消删除！')
      const { data: res } = await this.$http.delete(`goods/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除商品失败！')
      this.$message.success('删除商品成功！')
      this.getGoodsList()
    },
    // 获取所有商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('/categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      this.cateList = res.data
    },
    // 获取编辑商品的分类
    cateChange () {
      if (this.goodsForm.goods_cat.length !== 3) {
        this.$message.error('只能选择三级商品分类！')
        this.goodsForm.goods_cat = []
        return false
      }
    },
    // 处理商品图片预览效果
    handlePreview (file) {
      console.log(file)
      this.previewPath = file.url
      // 打开图片预览对话框
      this.previewDialogVisible = true
    },
    // 处理移除商品图片的操作
    handleRemove (file) {
      // 获取要移除图片的临时路径
      const filePath = file.url
      // 获得goodsForm中图片的索引值
      const i = this.goodsForm.pics.findIndex(item => item.pic === filePath)
      // 通过索引值移除图片
      this.goodsForm.pics.splice(i, 1)
    },
    // 监听图片上传成功的事件
    handleSuccess (response) {
      const picInfo = { pic: response.data.tmp_path }
      this.goodsForm.pics.push(picInfo)
    },
    setGoodsDialogClosed () {
      this.goodsForm.pics = []
    },
    // 跳转到添加商品页面
    toAddpage () {
      this.$router.push('/goods/add')
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
